<!--客户列表-->
<template>
  <view class="container client_container">
    <u-sticky offset-top="0">
      <view class="channel_tab">
        <u-tabs :list="tabsTitle" @change="tabschange" :current="activeKey" lineColor="#4A76F7" :inactiveStyle="{color: '#8091A4', fontSize: '28rpx'}" :activeStyle="{ color: '#333333', fontWeight: '500'}"></u-tabs>
        <view class="filter_icon">
          <tm-icon fontSize="24" name="iconfont icon-shaixuanweixuan" color="#999999" @click="openFilter" ></tm-icon>
        </view>
      </view>
    </u-sticky>

    <view class="channel_list">
      <view class="cur_customer">
        <text class="title_text">当前客户</text>
        <text class="title_sub_text">({{totalRows}})条</text>
      </view>
      <view v-for="(item,i) in customerListData" class="channel_item" :key="i" @click="()=>customerDetail(item)">
        <tm-sheet :margin="[24, 20]" :round="3" :shadow="2">
          <view class="channel_item_title">
            <view class="channel_type">
              <!--              1 待跟进  2 已上门  3 未上门 4已签约 5已流失-->
              <tm-tag v-if="item.status === 1" text :shadow="0" color="#165DFF" size="m" label="待跟进"></tm-tag>
              <tm-tag v-if="item.status === 2" text :shadow="0" color="#2ACFCE" size="m" label="已上门"></tm-tag>
              <tm-tag v-if="item.status === 3" text :shadow="0" color="#F5319D" size="m" label="未上门"></tm-tag>
              <tm-tag v-if="item.status === 4" text :shadow="0" color="#00B42A" size="m" label="已签约"></tm-tag>
              <tm-tag v-if="item.status === 5" text :shadow="0" color="#88929E" size="m" label="已流失"></tm-tag>
            </view>
            <view v-if="item.updated_at" class="sign_time">
              <text class="sign_text">最近跟进</text>
              <text class="sign_time_text">{{moment(item.follow_at).format('YYYY-MM-DD')}}</text>
            </view>
          </view>
          <view class="customer_item_head">
            <view >
              <image class="channel_item_type" src="@/static/img/client_header.png"></image>
            </view>
            <view class="customer_head_inner">
              <view class="inner_value"><text>{{item.contact_name? item.contact_name:'--'}}</text><text class="inner_soide_text">客户联系人</text></view>
              <view class="inner_phone">{{item.contact_mobile}}</view>
            </view>
            <view v-if="item.contact_mobile_style === 1" class="inner_phone_icon">
              <image   src="@/static/img/phone.png"></image>
              <text>联系</text>
            </view>
          </view>
          <view class="channel_item_content">
            <view class="cus_item">
              <view class="cus_item_label">客户名称</view>
              <view class="cus_item_value">{{item.name}}</view>
            </view>
            <view class="cus_item">
              <view class="cus_item_label">行业</view>
              <view class="cus_item_value">{{item.industry_text}}</view>
            </view>
            <view class="cus_item">
              <view class="cus_item_label">渠道来源</view>
              <view v-if="item.source_channel == 1" class="cus_item_value">中介渠道</view>
              <view v-if="item.source_channel == 2" class="cus_item_value">关系渠道</view>
              <view v-if="item.source_channel == 3" class="cus_item_value">推广渠道</view>
              <view v-if="item.source_channel == 4" class="cus_item_value">其他渠道</view>
            </view>
            <view class="cus_item">
              <view class="cus_item_label">预租面积</view>
              <view class="cus_item_value">{{item.pre_lease_area_min}}</view>
            </view>
            <view class="cus_item">
              <view class="cus_item_label">预算价格</view>
              <view class="cus_item_value">{{item.per_lease_price}}{{item.price_unit_text}}</view>
            </view>
          </view>
        </tm-sheet>
      </view>

    </view>

    <view class="cus_footer_btn">
      <tm-button block label="新建客户" round="25" @click="addChannel"></tm-button>
    </view>
    <!--     筛选框 -->
    <u-popup :show="filterVisible" @close="close" @open="open" mode="top" :round="10">
      <view class="zs_filter_main">
        <view class="zs_filter_title">搜索</view>
        <view class="zs_filter_item" style="padding-bottom: 24px;">
          <up-input
              customStyle="background-color:#F9F9F9"
              v-model="searchParams.keyword"
              placeholder="支持搜索客户名称/手机号"
              prefixIcon="search"
              suffixIcon="close-circle-fill"
              shape="circle"
              prefixIconStyle="font-size: 22px;color: #8091A4"
              placeholderStyle="color: #8091A4"
          ></up-input>
        </view>
        <view class="zs_filter_title">渠道来源</view>
        <view class="search_customer_channel">
          <view v-for="item in channelTypeOptions" :class="['srch_cust_cha_text', item.checked ? 'selected' : '']" :key="item.value" @click="() => switchChannelType(item)">{{item.label}}</view>
<!--          <view class="srch_cust_cha_text">关系渠道</view>-->
<!--          <view class="srch_cust_cha_text">推广渠道</view>-->
<!--          <view class="srch_cust_cha_text">其他渠道</view>-->
<!--          <u-tag text="标签" shape="circle" color="#8091A4" borderColor="#F9F9F9" bgColor="#F9F9F9"></u-tag>-->
        </view>
        <view class="zs_filter_title">跟进时间</view>
        <view class="zs_filter_item filter_range_time">
          <view class="filter_range" @click="() => selectTime(1)">
            <text v-if="searchParams.start_time">{{moment(searchParams.start_time).format("YYYY-MM-DD")}}</text>
            <text v-else style="color:#8091A4;">请选择</text>
          </view>
          <text>至</text>
          <view class="filter_range" @click="() => selectTime(2)">
            <text v-if="searchParams.end_time">{{moment(searchParams.end_time).format("YYYY-MM-DD")}}</text>
            <text v-else style="color:#8091A4;">请选择</text>
          </view>
        </view>
        <!--       选择时间弹框 -->
        <u-datetime-picker
            :show="timeVisible"
            v-model="searchValue"
            mode="date"
            @confirm="confirm"
            @cancel="cancelDatePick"
        ></u-datetime-picker>
        <view class="zs_filter_btns">
          <up-button type="primary" shape="circle" plain text="重置" @click="handleReset"></up-button>
          <up-button type="primary" shape="circle" text="搜索" @click="handleSearch"></up-button>
        </view>
      </view>
    </u-popup>

  </view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { customerList,customerCount } from '@/api_request/merchants'
import {onReachBottom, onShow} from '@dcloudio/uni-app';
import { each } from 'lodash'
import moment from "moment";
import {channelType} from '@/utils/dictionary'

const timeVisible = ref<boolean>(false)
const searchValue = ref<any>('')
const customerListData = ref<any>([])
const page_num = ref<number>(1)
const page_size = ref<number>(10)
const totalRows = ref<number>(0)
const activeKey = ref<number>(0)
const tabsTitle = ref([
  {
    name: '全部',
    badge: {
      value: 0,
    },
  },
  {
    name: '待跟进',
    type: 1,
    badge: {
      value: 0,
    }
  },
  {
    name: '未上门',
    type: 3,
    badge: {
      value: 0,
    }
  },
  {
    name: '已上门',
    type: 2,
    badge: {
      value: 0,
    }
  },
  {
    name: '已签约',
    type: 4,
    badge: {
      value: 0,
    }
  }
  ,
  {
    name: '已流失',
    type: 5,
    badge: {
      value: 0,
    }
  }
])
const channelTypeOptions = ref<any>(channelType)

const filterVisible = ref<boolean>(false)
const searchParams = ref<any>({
  keyword:'',
  source_channel:[],
  start_time: '',
  end_time: '',
})

onShow(()=>{
  if(uni.getStorageSync("refreshPage")){
    uni.removeStorageSync("refreshPage")
    page_num.value = 1
    customerListData.value = []
    initData()
    getCustomerList()
  }
})
//客户详情
const customerDetail =(customer)=>{
  uni.navigateTo({url:'/subpkg/client_detail/index?id='+customer.id})
}

const getCustomerList = (data?) => {
  customerList({page_num: page_num.value, page_size: page_size.value, ...searchParams.value, ...data}).then(res => {
    console.log('jp======客户列表',res)
    if(data && data.reachBottomFlag){
      customerListData.value = [...customerListData.value,...res.data.list]
    }else{
      customerListData.value = res.data.list
    }
    totalRows.value = res.data.total
    page_num.value = res.data.page_num
    tabsTitle.value[activeKey.value].badge.value = res.data.total
  })
}
getCustomerList()


const switchChannelType = (item) => {
  each(channelTypeOptions.value, (cItem) => {
    // cItem.checked = false
    if(cItem.value === item.value) {
      if(cItem.checked){
        cItem.checked = false
        searchParams.value.source_channel=searchParams.value.source_channel.filter(ele=>ele != item.value)
      }else{
        cItem.checked = true
        searchParams.value.source_channel.push(item.value)
      }
    }
  })
}
const initData = () => {
  customerCount({}).then(res => {
    console.log('jp=======客户统计',res)
    const __tabsTitle = [...tabsTitle.value]
    each(res.data, (item) =>{
      const index = __tabsTitle.findIndex(v => v.type === item.status)
      if(index !== -1) {
        __tabsTitle[index].badge.value = item.count
      }
    })
    tabsTitle.value = __tabsTitle
    console.log('jp======tabsTitle.value',tabsTitle.value)
  })
}
initData()

const tabschange = (tabItem) => {
  activeKey.value = tabItem.index
  getCustomerList(tabItem.type?{status: tabItem.type}:{})

}
const close = () => {
  filterVisible.value = false
}
const handleReset = () => {
  close()
  channelTypeOptions.value.forEach(ele=>ele.checked=false)
  page_num.value = 1
  searchParams.value = {}
  getCustomerList(tabsTitle.value[activeKey.value].type?{status: tabsTitle.value[activeKey.value].type}:{})
}
const handleSearch = () => {
  getCustomerList(tabsTitle.value[activeKey.value].type?{status: tabsTitle.value[activeKey.value].type}:{})
  close()
}
//  1: 选择开始时间    2：选择结束时间
const selectTimeType = ref<number>(1)
const selectTime = (type) => {
  timeVisible.value = true
  selectTimeType.value = type
}
// 选择时间
const confirm = (val) => {
  console.log('jp=======searchParams',searchParams)
  timeVisible.value = false
  if(selectTimeType.value === 1) {
    searchParams.value.start_time = val.value
    return
  }
  if(selectTimeType.value === 2) {
    searchParams.value.end_time = val.value
  }
}
//取消选择时间
const cancelDatePick = ()=>{
  timeVisible.value = false
}

const openFilter = () => {
  console.log('jp======打开搜索',)
  filterVisible.value = true
}

// 新建渠道
const addChannel = () => {
  uni.navigateTo({url: `/subpkg/create_client/index?title=新建客户`})
}
onReachBottom(() => {
  console.log('jp=======下拉刷新',customerListData.value?.length, totalRows.value)
  let curPage: number = 0
  if(customerListData.value?.length === totalRows.value) {
    return
  } else {
    curPage = page_num.value + 1
    let search = {page_num: curPage,reachBottomFlag:true}
    if(activeKey.value != 0){
      search.status = tabsTitle.value[activeKey.value].type
    }
    getCustomerList()
  }
})
</script>

<style lang="scss" scoped>
.filter_range{
  padding: 0px 0px 0px 10px;
}
.search_customer_channel{
  display: flex;
  justify-content: space-around;
  padding-bottom: 18px;
  .srch_cust_cha_text{
    height: 34px;
    padding: 0px 10px;
    border-radius: 17px;
    color: #8091A4;
    background-color: #F9F9F9;
    line-height: 34px;
  }
  .srch_cust_cha_text.selected{
    color: #165DFF;
    background-color: #E4EBFB;
  }
}


.client_container{
  font-size: $cus-font-size-14;
  .channel_tab{
    position: relative;
    padding-right: 30px;
    background: #fff;
    .filter_icon{
      position: absolute;
      top: 17px;
      right: 10px;
    }
  }


}
.zs_filter_btns{
  :deep(button) {
    width: 144px;
  }
}
:deep(.u-transition) {
  top: 53px!important;
}
</style>